package lex.mtd.core.net;

import org.lex.utils.Callback;

import lex.mtd.core.ContentLengthVerifier;
import lex.mtd.core.DataSourceSet;
import lex.mtd.core.DownloadObject;
import lex.mtd.core.SimpleContentLengthVerifier;
import lex.mtd.core.utils.LogSet;

public class ContentLengthFetcher implements DataSourceObserver
{
	private Callback<Long> callback = null;
	private DataSourceSet sourceSet = null;
	private ContentLengthVerifier verifier = null;

	public <T extends Callback<Long>> ContentLengthFetcher( DownloadObject task, LogSet logSet,
			T callback )
	{
		this.callback = callback;
		this.verifier = new SimpleContentLengthVerifier();
		this.sourceSet = new DataSourceSet( task.getURLSet(), this, logSet );
		this.sourceSet.start();
	}

	@Override
	public void dataSourceAvailable( DataSource source )
	{
		try
		{
			long len = source.getContentLength( 0 );
			synchronized( verifier )
			{
				if( true == verifier.verifyContentLength( len ) )
				{
					callback.receive( len );
					sourceSet.stop();
				}
				source.close();
			}
		}
		catch( Exception e )
		{}
	}
}
